<?php

namespace Sharks\Core\LifeCycle;

use ReflectionClass;
use Sharks\Core\AppContext;
use Sharks\Core\Module;

/**
 * 应用命令
 * php cmd $cmd:funcName $arg1 $arg2 ...
 */
abstract class Command {

    protected static $commands = null;

    /**
     * 新增
     * @param $cmd
     * @param $class
     */
    public static function add($cmd, $class) {
        if (is_null(self::$commands)) {
            self::$commands = array();
        }
        self::$commands[$cmd] = $class;
    }

    /**
     * 提取所有命令
     */
    public static function register() {
        self::$commands = array();
        $frameworkCmd = AppContext::instance()->path->framework->root . '/Command/cmd.php';
        require_once $frameworkCmd;
        $appCmd = AppContext::instance()->path->app->source . '/Command/cmd.php';

        if (file_exists($appCmd)) {
            require_once $appCmd;
        }
        foreach (Module::all() as $module) {
            if (file_exists($module->path->root . '/Command/cmd.php')) {
                require_once $module->path->root . '/Command/cmd.php';
            }
        }
    }

    /**
     * 执行相应的命令
     * @param $cmd
     * @param $func
     * @param $args
     */
    public static function execute($cmd, $func, $args) {
        if (isset(self::$commands[$cmd])) {
            $obj = new self::$commands[$cmd];
            call_user_func_array(array($obj. $func), $args);
        }
        else {
            echo "No Command Named $cmd" . PHP_EOL;
        }
    }
}